#pragma once
#include <string>
#include <iostream>
#include <cstring>
#include "error.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

namespace UDP_client
{
    class client
    {
    public:
        client(std::string ip, uint16_t port) : _ip(ip), _port(port)
        {
        }
        void start()
        {
            int _sock = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sock < 0)
            {
                std::cerr << "create socket error" << std::endl;
                exit(SOCKET_ERR);
            }
            // 明确server是谁
            struct sockaddr_in server;
            bzero(&server, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(_port);
            server.sin_addr.s_addr = inet_addr(_ip.c_str());
            while (true)
            {
                std::string message;
                std::cout << "请输入发送给serveer的信息: " << std::endl;
                std::getline(std::cin, message);
                // client 会在第一次发送数据时自动bind
                sendto(_sock, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));

                // 接受消息
                char buffer[1024];
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                ssize_t n = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
                if (n > 0)
                {
                    buffer[n] = '\0';
                    std::cout << buffer << std::endl;
                }
            }
        }
        ~client()
        {
            close(_sock);
        }

    private:
        int _sock;
        std::string _ip;
        uint16_t _port;
    };
}